import {PureComponent} from "react";
import {StoreContext} from "./storeContext";


export default function connect(mapStateToProps,mapDispatchToProps){

    return function (WrapperComponent){

        class NewComponent extends PureComponent{
            constructor(props,context) {
                // contextType会在componentDidMount后才会设置，，， 构造函数中获取不到 this.context,,
                super(props);
                // console.log(this.context,"context")
                this.state = context.getState()


            }

            componentDidMount() {
                this.context.subscribe(()=>{
                    this.setState(this.context.getState())
                })
            }

            render() {
                const stateObj = mapStateToProps(this.context.getState())
                const dispatchObj = mapDispatchToProps(this.context.dispatch)
                return <WrapperComponent {...this.props} {...stateObj} {...dispatchObj}/>
            }
        }

        // this.context 就是store
        NewComponent.contextType = StoreContext

        return NewComponent
    }
}
